package com.atlin.project.manager;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author atlin
 * @description
 * @createDate 2024/11/25 22:15
 */
@Component
@Slf4j
public class AlipayManager {

    /**
     * 支付成功重定向 上线地址
     */
    public static final String RETURNURL = "http://www.muyezi.icu/bi/my-service-usage";

    /**
     * 支付成功回调
     */
    public static final String NOTIFYURL = "http://www.muyezi.icu/api/pay/notification";

    @Resource
    private AlipayConfig alipayConfig;

    /**
     * 支付宝支付
     *
     * @param model 支付参数
     */
    public String pay(AlipayTradePagePayModel model) {
        // 创建API对应的request
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 支付宝回调地址
        request.setNotifyUrl(NOTIFYURL);
        request.setReturnUrl(RETURNURL);
        
        // 跳转模式
        model.setQrPayMode("2");

        // 设置商户自定义二维码宽度
        model.setQrcodeWidth(100L);

        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        request.setBizModel(model);

        AlipayTradePagePayResponse response = null;
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            response = alipayClient.pageExecute(request);
            return response.getBody();
        } catch (AlipayApiException e) {
            log.error("AlipayManager pay failure", e);
        }
        return "";
    }
}
